#!/usr/bin/env python
import sys
#import time
#import os.path

from PyQt4 import QtCore, QtGui

from play_frame import PlayFrame
from globals import *

class Pop(QtGui.QWidget):

  def __init__(self, x, y):
    QtGui.QWidget.__init__(self)
    self.key_funcs = {}
    self.frames_grid = []
    self.frames = []
    self.current_frame = None
    
    self.setPalette(PBLACK)
    self.setAutoFillBackground(False)
    self.resize(640,480)
    self.init_keys()
    self.init_frames(x, y)
    self.current_frame = self.frames[-1]
    self.next_frame()

  def init_frames(self, x, y):
    gridlayout = QtGui.QGridLayout(self)
    gridlayout.setMargin(0)
    gridlayout.setSpacing(0)
    #this sucks but i know no other way
    for j in range(0, int(x)):
      self.frames_grid.append([])
    for i in range(0, int(y)):
      for j in range(0, int(x)):
        pf = PlayFrame(self)
        self.frames_grid[j].append(pf)
        self.frames.append(pf)
        gridlayout.addWidget(pf, i, j, 1, 1)

  def init_keys(self):
    self.key_funcs[QtCore.Qt.Key_N] = self.next_frame
    self.key_funcs[QtCore.Qt.Key_B] = self.last_frame
    self.key_funcs[QtCore.Qt.Key_Delete] = self.next_frame
    self.key_funcs[QtCore.Qt.Key_F23] = self.next_frame
    self.key_funcs[QtCore.Qt.Key_Insert] = self.next_mov
    self.key_funcs[QtCore.Qt.Key_Comma] = self.next_mov
    self.key_funcs[QtCore.Qt.Key_Q] = self.quit_app
    self.key_funcs[QtCore.Qt.Key_F] = self.toggle_full_screen
    self.key_funcs[QtCore.Qt.Key_C] = self.decrackle

  def keyPressEvent(self, event):
    code = event.key()
    if code in self.key_funcs:
      self.key_funcs[code]()
    elif code in FRAME_KEYS or code in PLAYLIST:
      self.current_frame.hit_key(code)

  def move_frame(self, i):
    self.current_frame.setPalette(PBLACK)
    index = self.frames.index(self.current_frame)
    index += i
    if index < 0:
      index = len(self.frames) - 1
    elif index >= len(self.frames):
      index = 0
    self.current_frame = self.frames[index]
    self.current_frame.setPalette(PDGRAY)

  def next_frame(self):
    self.move_frame(1)

  def last_frame(self):
    self.move_frame(-1)

  def decrackle(self):
    for frame in self.frames:
      frame.decrackle()
      

  def next_mov(self):
    self.current_frame.hit_key(QtCore.Qt.Key_Less)

  def quit_app(self):
    for f in self.frames:
      f.quit()
      QtCore.QThread.sleep(1)
    QtGui.QApplication.quit()
    
  def toggle_full_screen(self):
    self.setWindowState(self.windowState() ^ QtCore.Qt.WindowFullScreen)

def main():
  app = QtGui.QApplication(sys.argv)
  print sys.argv[0]
  print sys.argv[1]
  pop = Pop(sys.argv[1], sys.argv[2])
  pop.show()
  sys.exit(app.exec_())


if __name__ == '__main__':
  main()
